#include "requestdialog.h"
#include "ui_requestdialog.h"
#include "mcform.h"

#include <QtDebug>
#include <QtSql>
#include <QtGui>

RequestDialog::RequestDialog(QWidget *parent) :
    QDialog(parent, Qt::Window),
    ui(new Ui::RequestDialog)
{
    ui->setupUi(this);

    layout = new QVBoxLayout();
    ui->groupBox->setLayout(layout);

    ui->request_comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);
    ui->give_comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);
    ui->by_whom_comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);
    ui->recipient_comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);
    ui->department_comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);
    ui->store_comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);

    ui->dateEdit->setDate(QDate::currentDate());

    loadData();

    readSettings();

    buttonsSetup();
}

RequestDialog::~RequestDialog()
{
    delete ui;
}

void RequestDialog::addMc(McForm *form)
{
    if(layout->count() < qApp->property("MaxNumOfRows").toInt()){
        if(!form) form = new McForm(ui->groupBox);
        form->disconnect();
        connect(form, SIGNAL(check()), this, SLOT(checkLine()));
        layout->addWidget(form);
        form->setNumber(layout->count());
        QString row = (layout->count() == 1 ? tr("row") : tr("rows"));
        setWindowTitle(tr("Request (%1 %2)")
                       .arg(layout->count())
                       .arg(row)
                       );
        form->show();
    }
    buttonsSetup();
}

void RequestDialog::removeMc()
{
    if(layout->count() > 1){
        int num = 0;
        for(int i=0;i<layout->count();i++){
            McForm* f = qobject_cast<McForm *>(layout->itemAt(i)->widget());
            if(f){
                if(f->isChecked()){
                    delete f;
                    i--;
                }
                else f->setNumber(++num);
            }
        }
        QString row = (num <= 1 ? tr("row") : tr("rows"));
        setWindowTitle(tr("Request (%1 %2)")
                   .arg(num)
                   .arg(row)
                   );
    }
    buttonsSetup();
}

void RequestDialog::buttonsSetup()
{
    bool add = layout->count() < qApp->property("MaxNumOfRows").toInt();
    bool ok = layout->count() > 0;
    bool rem = true;

    for(int i=0;i<layout->count();i++){
        McForm* f = qobject_cast<McForm *>(layout->itemAt(i)->widget());
        if(f){
            rem = f->isChecked();
            if(rem) break;
        }
    }
    rem = rem && layout->count() > 1;

    ui->add_toolButton->setEnabled(add);
    ui->remove_toolButton->setEnabled(rem);
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
}

void RequestDialog::loadData()
{
    QSqlTableModel* model = new QSqlTableModel(this);
    model->setTable("requests");
    model->select();

    QSqlTableModel* omodel = new QSqlTableModel(this);
    omodel->setTable("organizations");
    omodel->select();

    QStringList organization;
    for(int i=0; i<omodel->rowCount(); i++){
        QSqlRecord record = omodel->record(i);
        if(record.isEmpty()) break;
        organization << record.value("organization").toString();
    }
    organization.removeDuplicates();

    QStringList destination;
    for(int i=0; i<model->rowCount(); i++){
        QSqlRecord record = model->record(i);
        if(record.isEmpty()) break;
        destination << record.value("destination").toString();
    }
    destination.removeDuplicates();

    QCompleter *ocompleter = new QCompleter(organization, this);
    ocompleter->setCompletionMode(QCompleter::PopupCompletion);
    ui->organization_comboBox->clear();
    ui->organization_comboBox->setCompleter(ocompleter);
    ui->organization_comboBox->addItems(organization);

    QCompleter *dcompleter = new QCompleter(destination, this);
    dcompleter->setCompletionMode(QCompleter::PopupCompletion);
    ui->destination_comboBox->clear();
    ui->destination_comboBox->setCompleter(dcompleter);
    ui->destination_comboBox->addItems(destination);


    QSqlTableModel* operators_model = new QSqlTableModel(this);
    operators_model->setTable("operators");
    operators_model->select();

    ui->request_comboBox->setModel(operators_model);
    ui->request_comboBox->setModelColumn(operators_model->fieldIndex("name"));
    ui->request_comboBox->setCurrentIndex(0);

    ui->give_comboBox->setModel(operators_model);
    ui->give_comboBox->setModelColumn(operators_model->fieldIndex("name"));
    ui->give_comboBox->setCurrentIndex(0);

    ui->by_whom_comboBox->setModel(operators_model);
    ui->by_whom_comboBox->setModelColumn(operators_model->fieldIndex("name"));
    ui->by_whom_comboBox->setCurrentIndex(0);

    ui->recipient_comboBox->setModel(operators_model);
    ui->recipient_comboBox->setModelColumn(operators_model->fieldIndex("name"));
    ui->recipient_comboBox->setCurrentIndex(0);

    QSqlTableModel* departments_model = new QSqlTableModel(this);
    departments_model->setTable("departments");
    departments_model->select();

    ui->department_comboBox->setModel(departments_model);
    ui->department_comboBox->setModelColumn(departments_model->fieldIndex("department"));
    ui->department_comboBox->setCurrentIndex(0);

    QSqlTableModel* stores_model = new QSqlTableModel(this);
    stores_model->setTable("stores");
    stores_model->select();

    ui->store_comboBox->setModel(stores_model);
    ui->store_comboBox->setModelColumn(stores_model->fieldIndex("store"));
    ui->store_comboBox->setCurrentIndex(0);

    delete model;
}

void RequestDialog::accept()
{
    saveSettings();
    QDialog::accept();
}

void RequestDialog::reject()
{
    saveSettings();
    QDialog::reject();
}

bool RequestDialog::insertRecord()
{
    //check for filled items rows!
    QSqlQuery* query = new QSqlQuery(QSqlDatabase::database());

    if(!query->exec(QString("INSERT INTO `requests` (`date`,`organization`,`department`,`destination`,"
                            "`request`,`give`,`by_whom`,`recipient`, `store`)"
                            "VALUES('%1','%2','%3','%4','%5','%6','%7','%8','%9')")
                    //.arg(ui->dateEdit->date().toString("MM.yyyy"))
                    .arg(ui->dateEdit->date().toString("yyyy-MM-dd"))
                    .arg(ui->organization_comboBox->currentText())
                    .arg(ui->department_comboBox->currentText())
                    .arg(ui->destination_comboBox->currentText())
                    .arg(ui->request_comboBox->currentText())
                    .arg(ui->give_comboBox->currentText())
                    .arg(ui->by_whom_comboBox->currentText())
                    .arg(ui->recipient_comboBox->currentText())
                    .arg(ui->store_comboBox->currentText())
                    )){
        qDebug() << "SQL error: " << query->lastError().text();
        QMessageBox msgBox;
        msgBox.setText(query->lastError().text());
        msgBox.exec();
        return false;
    }
    int req_id = query->lastInsertId().toInt();
    for(int n=0; n<layout->count(); ++n){
         QWidget* w = layout->itemAt(n)->widget();
         McForm* f = qobject_cast<McForm *>(w);
         if(f){
             if(!f->insertRecord(req_id)) return false;
         }
    }
    if(!ui->department_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `departments` (`department`) VALUES('%1')")
                       .arg(ui->department_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->department_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `departments` (`department`) VALUES('%1')")
                       .arg(ui->department_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->request_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->request_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->give_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->give_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->by_whom_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->by_whom_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->recipient_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->recipient_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->store_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `stores` (`store`,`operator_id`) VALUES('%1', 1)")
                       .arg(ui->store_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    return true;
}

void RequestDialog::setRequest(const int req_id)
{
    QSqlQuery* query = new QSqlQuery(QSqlDatabase::database());
    if(!query->exec(QString("SELECT * FROM `requests` WHERE `id`='%1'").arg(req_id))){
        qDebug() << "Sql Error: " << query->lastError().text();
        QMessageBox msgBox;
        msgBox.setText(query->lastError().text());
        msgBox.exec();
        return;
    }
    if(!query->first()) return;
    QSqlRecord rec = query->record();
    QDate dt = QDate::fromString(query->value(rec.indexOf("date")).toString(), "yyyy-MM-dd");
    if(!dt.isValid()){
        dt = QDate::fromString(query->value(rec.indexOf("date")).toString(), "dd.MM.yyyy");
    }
    ui->dateEdit->setDate(dt);
    ui->organization_comboBox->setEditText(query->value(rec.indexOf("organization")).toString());
    ui->department_comboBox->setText(query->value(rec.indexOf("department")).toString());
    ui->destination_comboBox->setEditText(query->value(rec.indexOf("destination")).toString());
    ui->request_comboBox->setText(query->value(rec.indexOf("request")).toString());
    ui->give_comboBox->setText(query->value(rec.indexOf("give")).toString());
    ui->by_whom_comboBox->setText(query->value(rec.indexOf("by_whom")).toString());
    ui->recipient_comboBox->setText(query->value(rec.indexOf("recipient")).toString());
    ui->store_comboBox->setEditText(query->value(rec.indexOf("store")).toString());


    if(!query->exec(QString("SELECT `id` FROM `requests_details` WHERE `request_id`='%1'").arg(req_id))){
        qDebug() << "Sql Error: " << query->lastError().text();
        QMessageBox msgBox;
        msgBox.setText(query->lastError().text());
        msgBox.exec();
        return;
    }
    while (query->next() && query->at() < qApp->property("MaxNumOfRows").toInt()) {
        McForm* form = new McForm(this);
        form->setItem(query->value(0).toInt());
        addMc(form);
    }
}

bool RequestDialog::updateRecord(const int req_id)
{
    //check for filled items rows!
    QSqlQuery* query = new QSqlQuery(QSqlDatabase::database());

    if(!query->exec(QString("UPDATE `requests` SET `date`='%1',`organization`='%2',`department`='%3',`destination`='%4',"
                            "`request`='%5',`give`='%6',`by_whom`='%7',`recipient`='%8', `store`='%9' WHERE `id`='%10'")
                    .arg(ui->dateEdit->date().toString("yyyy-MM-dd"))
                    .arg(ui->organization_comboBox->currentText())
                    .arg(ui->department_comboBox->currentText())
                    .arg(ui->destination_comboBox->currentText())
                    .arg(ui->request_comboBox->currentText())
                    .arg(ui->give_comboBox->currentText())
                    .arg(ui->by_whom_comboBox->currentText())
                    .arg(ui->recipient_comboBox->currentText())
                    .arg(ui->store_comboBox->currentText())
                    .arg(req_id)
                    )){
        qDebug() << "SQL error: " << query->lastError().text();
        QMessageBox msgBox;
        msgBox.setText(query->lastError().text());
        msgBox.exec();
        return false;
    }
    if(!query->exec(QString("DELETE FROM `requests_details` WHERE `request_id`='%1'").arg(req_id))){
        qDebug() << "SQL error: " << query->lastError().text();
        QMessageBox msgBox;
        msgBox.setText(query->lastError().text());
        msgBox.exec();
        return false;
    }
    for(int n=0; n<layout->count(); ++n){
         QWidget* w = layout->itemAt(n)->widget();
         McForm* f = qobject_cast<McForm *>(w);
         if(f){
             if(!f->insertRecord(req_id)) return false;
         }
    }
    if(!ui->department_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `departments` (`department`) VALUES('%1')")
                       .arg(ui->department_comboBox->currentText())
                       )){
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
            qDebug() << "Sql Error: " << query->lastError().text();
        }
    }
    if(!ui->department_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `departments` (`department`) VALUES('%1')")
                       .arg(ui->department_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->request_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->request_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->give_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->give_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->by_whom_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->by_whom_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->recipient_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `operators` (`name`,`department_id`) VALUES('%1', 1)")
                       .arg(ui->recipient_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    if(!ui->store_comboBox->hasInDatabase()){
        if(!query->exec(QString("INSERT INTO `stores` (`store`,`operator_id`) VALUES('%1', 1)")
                       .arg(ui->store_comboBox->currentText())
                       )){
            qDebug() << "Sql Error: " << query->lastError().text();
            QMessageBox msgBox;
            msgBox.setText(query->lastError().text());
            msgBox.exec();
        }
    }
    return true;
}


void RequestDialog::on_store_comboBox_currentIndexChanged(int /*index*/)
{
    if(ui->store_comboBox->hasInDatabase()){
        QSqlQuery* query = new QSqlQuery(QSqlDatabase::database());
        if(query->exec(QString("SELECT `name` FROM `operators` WHERE `id`="
                                "(SELECT `operator_id` FROM `stores` WHERE `id`='%1')")
                        .arg(ui->store_comboBox->itemModelId())
                        )){
            if(query->first()){
                ui->give_comboBox->setText(query->value(0).toString());
            }
        }
    }
}

void RequestDialog::checkLine()
{
    buttonsSetup();
}

void RequestDialog::readSettings()
 {
    QDir appdir = qApp->applicationDirPath();
    QSettings settings(appdir.filePath("Request.ini"), QSettings::IniFormat);
    settings.beginGroup("Program");
    settings.beginGroup("RequestWindow");
    restoreGeometry(settings.value("Geometry").toByteArray());
    settings.endGroup();
    settings.endGroup();
 }

void RequestDialog::saveSettings()
{
    QDir appdir = qApp->applicationDirPath();
    QSettings settings(appdir.filePath("Request.ini"), QSettings::IniFormat);
    settings.beginGroup("Program");
    settings.beginGroup("RequestWindow");
    settings.setValue("Geometry", saveGeometry());
    settings.endGroup();
    settings.endGroup();
}
